package com.rxy.api;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

public class UpdateNodeData implements Watcher {

    // 计数工具类，让线程处于等待阻塞，主要不让main方法结束
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static ZooKeeper zooKeeper;

    public static void main(String[] args) throws Exception {
        // 客户端可以通过创建一个zk实例来连接zk服务器
        zooKeeper = new ZooKeeper("192.168.31.247:2181",
                5000, new UpdateNodeData());
        // 让会话一直保持着
        Thread.sleep(Integer.MAX_VALUE);
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        try {
            updateNodeSync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改节点数据
     */
    private void updateNodeSync() throws Exception {
        /**
         * zooKeeper.setData(path, data,version);
         * path：路径
         * data：要修改的内容 byte[]
         * version：为-1，表示对最新版本的数据进行修改
         */
        byte[] data = zooKeeper.getData("/rxy-persistent", false, null);
        System.out.println("修改前的值:"+new String(data));
        // 修改数据，stat:状态信息对象
        Stat stat = zooKeeper.setData("/rxy-persistent", "客户端修改内容".getBytes(), -1);
        byte[] data2 = zooKeeper.getData("/rxy-persistent", false, null);
        System.out.println("修改后的值:"+new String(data2));
    }
}
